<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Smart Travel Poster Generator - ATP</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Playfair+Display:wght@400;500;600;700&display=swap" rel="stylesheet">
    <!-- Add html2canvas library -->
    <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #786CFF 0%, #6B5FE6 100%);
            min-height: 100vh;
            padding: 2rem;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            gap: 2rem;
        }

        .upload-section {
            flex: 1;
            background: white;
            border-radius: 20px;
            padding: 2rem;
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.2);
            height: fit-content;
        }

        .poster-section {
            flex: 1;
            position: sticky;
            top: 2rem;
        }

        .back-btn {
            position: absolute;
            top: 20px;
            left: 20px;
            background: rgba(255, 255, 255, 0.2);
            color: white;
            padding: 0.5rem 1rem;
            text-decoration: none;
            border-radius: 20px;
            font-size: 0.9rem;
            backdrop-filter: blur(10px);
            z-index: 10;
        }

        .upload-title {
            font-family: 'Playfair Display', serif;
            font-size: 2rem;
            color: #333;
            margin-bottom: 1rem;
            text-align: center;
        }

        .upload-subtitle {
            color: #666;
            text-align: center;
            margin-bottom: 2rem;
            font-size: 1.1rem;
        }

        /* Template Selector */
        .template-selector {
            margin-bottom: 2rem;
            text-align: center;
        }

        .template-selector h3 {
            font-size: 1.2rem;
            color: #333;
            margin-bottom: 1rem;
        }

        .template-options {
            display: flex;
            gap: 1rem;
            justify-content: center;
            flex-wrap: wrap;
        }

        .template-option {
            padding: 0.8rem 1.5rem;
            border: 2px solid #e9ecef;
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
            font-size: 0.9rem;
            font-weight: 500;
        }

        .template-option.active {
            border-color: #786CFF;
            background: linear-gradient(135deg, #786CFF, #6B5FE6);
            color: white;
        }

        .template-option:hover {
            border-color: #786CFF;
            transform: translateY(-2px);
        }

        /* Image Mode Selector */
        .image-mode-selector {
            margin-bottom: 2rem;
            text-align: center;
        }

        .image-mode-selector h3 {
            font-size: 1.1rem;
            color: #333;
            margin-bottom: 0.8rem;
        }

        .image-mode-options {
            display: flex;
            gap: 0.8rem;
            justify-content: center;
        }

        .image-mode-option {
            padding: 0.6rem 1.2rem;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .image-mode-option.active {
            border-color: #28a745;
            background: #28a745;
            color: white;
        }

        .image-mode-option:hover {
            border-color: #28a745;
            transform: translateY(-1px);
        }

        /* Poster Size Selector */
        .poster-size-selector {
            margin-bottom: 2rem;
            text-align: center;
        }

        .poster-size-selector h3 {
            font-size: 1.1rem;
            color: #333;
            margin-bottom: 0.8rem;
        }

        .poster-size-options {
            display: flex;
            gap: 0.8rem;
            justify-content: center;
        }

        .poster-size-option {
            padding: 0.6rem 1.2rem;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .poster-size-option.active {
            border-color: #17a2b8;
            background: #17a2b8;
            color: white;
        }

        .poster-size-option:hover {
            border-color: #17a2b8;
            transform: translateY(-1px);
        }

        /* Frame Style Selector for Timeline */
        .frame-style-selector {
            margin-bottom: 2rem;
            text-align: center;
        }

        .frame-style-selector h3 {
            font-size: 1.1rem;
            color: #333;
            margin-bottom: 0.8rem;
        }

        .frame-style-options {
            display: flex;
            gap: 0.8rem;
            justify-content: center;
            flex-wrap: wrap;
        }

        .frame-style-option {
            padding: 0.6rem 1.2rem;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .frame-style-option.active {
            border-color: #786CFF;
            background: linear-gradient(135deg, #786CFF, #6B5FE6);
            color: white;
        }

        .frame-style-option:hover {
            border-color: #786CFF;
            transform: translateY(-1px);
        }

        /* Flag Position Selector */
        .flag-position-selector {
            margin-bottom: 2rem;
            text-align: center;
            display: none;
        }

        .flag-position-selector h3 {
            font-size: 1.1rem;
            color: #333;
            margin-bottom: 0.8rem;
        }

        .flag-position-options {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 0.5rem;
            justify-content: center;
        }

        .flag-position-option {
            padding: 0.5rem 0.8rem;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .flag-position-option.active {
            border-color: #28a745;
            background: #28a745;
            color: white;
        }

        .flag-position-option:hover {
            border-color: #28a745;
            transform: translateY(-1px);
        }

        /* Collage Controls */
        .collage-controls {
            margin-bottom: 2rem;
            text-align: center;
            display: none;
        }

        .collage-controls h3 {
            font-size: 1.1rem;
            color: #333;
            margin-bottom: 0.8rem;
        }

        .collage-control-info {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 1rem;
            font-size: 0.9rem;
            color: #666;
        }

        .selected-image-info {
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px solid #e9ecef;
            display: none;
        }

        .selected-image-info h4 {
            color: #333;
            margin-bottom: 0.8rem;
            font-size: 1rem;
        }

        .control-group {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin-bottom: 0.8rem;
            text-align: left;
        }

        .control-group label {
            font-size: 0.8rem;
            color: #333;
            min-width: 80px;
        }

        .control-group input[type="range"] {
            flex: 1;
            height: 4px;
            background: #e9ecef;
            border-radius: 2px;
            outline: none;
        }

        .control-group input[type="range"]::-webkit-slider-thumb {
            appearance: none;
            width: 16px;
            height: 16px;
            background: #6f42c1;
            border-radius: 50%;
            cursor: pointer;
        }

        .control-group span {
            font-size: 0.8rem;
            color: #666;
            min-width: 40px;
        }

        .control-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 0.4rem 0.8rem;
            border-radius: 6px;
            font-size: 0.8rem;
            cursor: pointer;
            transition: background 0.3s ease;
        }

        .control-btn:hover {
            background: #c82333;
        }

        /* Upload Area */
        .upload-area {
            border: 3px dashed #786CFF;
            border-radius: 16px;
            padding: 3rem 2rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 2rem;
        }

        .upload-area:hover {
            border-color: #6B5FE6;
            background: rgba(120, 108, 255, 0.05);
        }

        .upload-area.dragover {
            border-color: #6B5FE6;
            background: rgba(120, 108, 255, 0.1);
        }

        .upload-icon {
            font-size: 3rem;
            color: #786CFF;
            margin-bottom: 1rem;
        }

        .upload-text {
            font-size: 1.1rem;
            color: #333;
            margin-bottom: 0.5rem;
        }

        .upload-hint {
            color: #666;
            font-size: 0.9rem;
        }

        #fileInput {
            display: none;
        }

        .uploaded-images {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .image-preview {
            position: relative;
            aspect-ratio: 1;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .image-preview img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .remove-image {
            position: absolute;
            top: 4px;
            right: 4px;
            background: rgba(255, 255, 255, 0.9);
            border: none;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            cursor: pointer;
            font-size: 0.8rem;
            color: #dc3545;
        }

        .analyze-btn {
            width: 100%;
            background: linear-gradient(135deg, #786CFF, #6B5FE6);
            color: white;
            border: none;
            padding: 1rem 2rem;
            border-radius: 12px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 2rem;
        }

        .analyze-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(120, 108, 255, 0.3);
        }

        .analyze-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        /* Download Button */
        .download-btn {
            width: 100%;
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            border: none;
            padding: 1rem 2rem;
            border-radius: 12px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 1rem;
            display: none;
        }

        .download-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(40, 167, 69, 0.3);
        }

        .download-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .download-btn.show {
            display: block;
        }

        .download-btn.downloading {
            background: linear-gradient(135deg, #6c757d, #495057);
            cursor: not-allowed;
        }

        .download-btn.downloading::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
            animation: downloading 1.5s infinite;
        }

        @keyframes downloading {
            0% { left: -100%; }
            100% { left: 100%; }
        }

        .download-success {
            background: linear-gradient(135deg, #28a745, #20c997) !important;
            animation: downloadSuccess 0.6s ease;
        }

        @keyframes downloadSuccess {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }

        /* Loading */
        .loading {
            display: none;
            text-align: center;
            padding: 2rem;
            color: #666;
        }

        .loading.active {
            display: block;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #786CFF;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 1rem;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* Poster Styles */
        .poster {
            width: 100%;
            max-width: 450px;
            min-height: 800px;
            background: white;
            border-radius: 20px;
            position: relative;
            overflow: hidden;
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.2);
            margin: 0 auto;
            transition: all 0.3s ease;
        }

        .poster.size-small {
            max-width: 360px;
            min-height: 640px;
        }

        .poster.size-medium {
            max-width: 450px;
            min-height: 800px;
        }

        .poster.size-large {
            max-width: 600px;
            min-height: 1000px;
        }

        .poster-header {
            background: linear-gradient(135deg, #786CFF, #6B5FE6);
            color: white;
            padding: 2rem;
            text-align: center;
            position: relative;
        }

        .poster-title {
            font-family: 'Playfair Display', serif;
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        .poster-subtitle {
            font-size: 1rem;
            opacity: 0.9;
        }

        .poster-content {
            padding: 1.5rem;
        }

        /* Template 1: Timeline */
        .template-timeline .photo-moment {
            margin-bottom: 2rem;
            background: #f8f9fa;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }

        .template-timeline .photo-moment:last-child {
            margin-bottom: 0;
        }

        /* Modern Frame Style (默认) */
        .template-timeline .photo-moment.frame-modern {
            background: #f8f9fa;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        /* Polaroid Frame Style */
        .template-timeline .photo-moment.frame-polaroid {
            background: #ffffff;
            border-radius: 8px;
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
            border: 8px solid #ffffff;
            transform: rotate(var(--frame-rotation, 0deg));
        }

        .template-timeline .photo-moment.frame-polaroid .moment-info {
            background: #ffffff;
            padding: 1.5rem;
            border-top: 1px solid #f0f0f0;
        }

        .template-timeline .photo-moment.frame-polaroid::before {
            content: '';
            position: absolute;
            top: -5px;
            left: 50%;
            transform: translateX(-50%);
            width: 40px;
            height: 20px;
            background: rgba(255, 255, 255, 0.8);
            border-radius: 0 0 50% 50%;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        /* Vintage Frame Style */
        .template-timeline .photo-moment.frame-vintage {
            background: linear-gradient(145deg, #f4f1e8, #e8e3d3);
            border-radius: 20px;
            box-shadow: 
                0 8px 25px rgba(0, 0, 0, 0.2),
                inset 0 1px 3px rgba(255, 255, 255, 0.3);
            border: 4px solid #d4af37;
            position: relative;
        }

        .template-timeline .photo-moment.frame-vintage::before {
            content: '';
            position: absolute;
            top: -8px;
            left: -8px;
            right: -8px;
            bottom: -8px;
            background: linear-gradient(45deg, #d4af37, #ffd700, #d4af37);
            border-radius: 24px;
            z-index: -1;
        }

        .template-timeline .photo-moment.frame-vintage .moment-info {
            background: linear-gradient(145deg, #f9f6f0, #f0ead6);
            color: #5d4e37;
        }

        /* Film Frame Style */
        .template-timeline .photo-moment.frame-film {
            background: #1a1a1a;
            border-radius: 4px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.4);
            border: 2px solid #333;
            position: relative;
        }

        .template-timeline .photo-moment.frame-film::before {
            content: '';
            position: absolute;
            top: -6px;
            left: -6px;
            right: -6px;
            bottom: -6px;
            background: repeating-linear-gradient(
                to right,
                #333 0px,
                #333 10px,
                #555 10px,
                #555 15px
            );
            border-radius: 8px;
            z-index: -1;
        }

        .template-timeline .photo-moment.frame-film .moment-image {
            border-radius: 2px;
        }

        .template-timeline .photo-moment.frame-film .moment-info {
            background: #2a2a2a;
            color: #e0e0e0;
        }

        .template-timeline .photo-moment.frame-film .time-stamp {
            color: #ccc;
        }

        .template-timeline .photo-moment.frame-film .location {
            background: #444;
            color: #fff;
        }

        .template-timeline .photo-moment.frame-film .mood-indicator {
            color: #e0e0e0;
        }

        .template-timeline .photo-moment.frame-film .moment-thought {
            color: #e0e0e0;
        }

        .template-timeline .photo-moment.frame-film .moment-time {
            border-bottom: 1px solid #444;
        }

        /* Decorative Frame Style */
        .template-timeline .photo-moment.frame-decorative {
            background: #fff;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            border: 3px solid transparent;
            background-clip: padding-box;
            position: relative;
        }

        .template-timeline .photo-moment.frame-decorative::before {
            content: '';
            position: absolute;
            top: -3px;
            left: -3px;
            right: -3px;
            bottom: -3px;
            background: linear-gradient(45deg, #ff6b6b, #4ecdc4, #45b7d1, #96ceb4, #ffeaa7, #dda0dd);
            border-radius: 19px;
            z-index: -1;
        }

        .template-timeline .photo-moment.frame-decorative .moment-info {
            background: #fff;
            position: relative;
        }

        .template-timeline .photo-moment.frame-decorative .moment-info::before {
            content: '✨';
            position: absolute;
            top: -10px;
            right: 10px;
            font-size: 1.2rem;
            background: #fff;
            padding: 0 5px;
            border-radius: 50%;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        /* Frame rotation variations */
        .template-timeline .photo-moment:nth-child(odd).frame-polaroid {
            --frame-rotation: -1.5deg;
        }

        .template-timeline .photo-moment:nth-child(even).frame-polaroid {
            --frame-rotation: 1.2deg;
        }

        .template-timeline .photo-moment:nth-child(3n).frame-polaroid {
            --frame-rotation: -0.8deg;
        }

        /* Hover effects for different frame styles */
        .template-timeline .photo-moment.frame-modern:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        }

        .template-timeline .photo-moment.frame-polaroid:hover {
            transform: rotate(var(--frame-rotation, 0deg)) translateY(-5px) scale(1.02);
            box-shadow: 0 12px 30px rgba(0, 0, 0, 0.2);
        }

        .template-timeline .photo-moment.frame-vintage:hover {
            transform: translateY(-5px);
            box-shadow: 
                0 15px 35px rgba(0, 0, 0, 0.25),
                inset 0 1px 3px rgba(255, 255, 255, 0.4);
        }

        .template-timeline .photo-moment.frame-film:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.5);
        }

        .template-timeline .photo-moment.frame-decorative:hover {
            transform: translateY(-5px) scale(1.02);
            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.2);
        }

        /* Additional decorative elements */
        .template-timeline .photo-moment.frame-vintage .moment-info::before {
            content: '🏛️';
            position: absolute;
            top: -10px;
            left: 10px;
            font-size: 1.2rem;
            background: linear-gradient(145deg, #f9f6f0, #f0ead6);
            padding: 0 5px;
            border-radius: 50%;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .template-timeline .photo-moment.frame-film .moment-info::before {
            content: '🎬';
            position: absolute;
            top: -10px;
            left: 10px;
            font-size: 1.2rem;
            background: #2a2a2a;
            color: #fff;
            padding: 0 5px;
            border-radius: 50%;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
        }

        /* Tape effect for polaroid frames */
        .template-timeline .photo-moment.frame-polaroid .moment-info::after {
            content: '';
            position: absolute;
            top: -15px;
            right: 20px;
            width: 30px;
            height: 15px;
            background: rgba(255, 255, 255, 0.7);
            border: 1px solid rgba(0, 0, 0, 0.1);
            border-radius: 2px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            transform: rotate(25deg);
        }

        /* Sparkle animation for decorative frames */
        @keyframes sparkle {
            0%, 100% { opacity: 0; transform: scale(0.8); }
            50% { opacity: 1; transform: scale(1.2); }
        }

        .template-timeline .photo-moment.frame-decorative .moment-info::after {
            content: '✨';
            position: absolute;
            top: -10px;
            left: 10px;
            font-size: 1rem;
            animation: sparkle 2s infinite;
            animation-delay: 0.5s;
        }

        /* Template 2: Map */
        .template-map {
            background: linear-gradient(135deg, #e3f2fd 0%, #fff3e0 100%);
            position: relative;
            overflow: visible;
        }

        /* Map Theme Variations */
        .template-map.theme-ocean {
            background: linear-gradient(135deg, #e0f2f1 0%, #b2dfdb 50%, #80cbc4 100%);
        }

        .template-map.theme-forest {
            background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 50%, #a5d6a7 100%);
        }

        .template-map.theme-desert {
            background: linear-gradient(135deg, #fff8e1 0%, #ffecb3 50%, #ffe082 100%);
        }

        .template-map.theme-city {
            background: linear-gradient(135deg, #f3e5f5 0%, #e1bee7 50%, #ce93d8 100%);
        }

        .template-map .poster-header {
            background: transparent;
            color: #333;
            padding: 1.5rem 1.5rem 0.5rem;
            text-align: center;
        }

        .template-map .poster-title {
            color: #d32f2f;
            font-size: 2.5rem;
            font-weight: 700;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 0.5rem;
        }

        .template-map .poster-subtitle {
            color: #333;
            font-size: 1rem;
            font-style: italic;
            opacity: 0.8;
        }

        .template-map .map-background {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 600"><defs><pattern id="grid" width="20" height="20" patternUnits="userSpaceOnUse"><path d="M 20 0 L 0 0 0 20" fill="none" stroke="%23e0e0e0" stroke-width="0.5"/></pattern></defs><rect width="400" height="600" fill="url(%23grid)"/><path d="M50 200 Q150 180 250 220 T350 240 Q320 300 280 350 Q200 400 150 380 Q100 350 80 300 Q60 250 50 200" fill="none" stroke="%23b0bec5" stroke-width="2" stroke-dasharray="5,5"/></svg>') center/cover;
            opacity: 0.3;
            z-index: 0;
        }

        /* Theme-specific map backgrounds */
        .template-map.theme-ocean .map-background {
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 600"><defs><pattern id="waves" width="40" height="20" patternUnits="userSpaceOnUse"><path d="M0 10 Q10 0 20 10 T40 10" fill="none" stroke="%23006064" stroke-width="1" opacity="0.3"/></pattern></defs><rect width="400" height="600" fill="url(%23waves)"/></svg>') center/cover;
        }

        .template-map.theme-forest .map-background {
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 600"><defs><pattern id="trees" width="30" height="30" patternUnits="userSpaceOnUse"><circle cx="15" cy="15" r="3" fill="%23388e3c" opacity="0.3"/><path d="M15 18 L15 25" stroke="%235d4037" stroke-width="2" opacity="0.3"/></pattern></defs><rect width="400" height="600" fill="url(%23trees)"/></svg>') center/cover;
        }

        .template-map.theme-desert .map-background {
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 600"><defs><pattern id="sand" width="25" height="25" patternUnits="userSpaceOnUse"><circle cx="12" cy="12" r="1" fill="%23f57f17" opacity="0.2"/><circle cx="5" cy="20" r="1" fill="%23ff8f00" opacity="0.2"/><circle cx="20" cy="5" r="1" fill="%23ffa000" opacity="0.2"/></pattern></defs><rect width="400" height="600" fill="url(%23sand)"/></svg>') center/cover;
        }

        .template-map.theme-city .map-background {
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 600"><defs><pattern id="buildings" width="50" height="40" patternUnits="userSpaceOnUse"><rect x="5" y="20" width="8" height="15" fill="%23424242" opacity="0.2"/><rect x="15" y="15" width="6" height="20" fill="%23616161" opacity="0.2"/><rect x="25" y="18" width="10" height="17" fill="%23757575" opacity="0.2"/><rect x="38" y="22" width="7" height="13" fill="%23424242" opacity="0.2"/></pattern></defs><rect width="400" height="600" fill="url(%23buildings)"/></svg>') center/cover;
        }

        .template-map .poster-content {
            position: relative;
            z-index: 1;
            padding: 1rem;
            min-height: 650px;
        }

        /* Pin Styles */
        .template-map .photo-pin {
            position: absolute;
            background: white;
            border-radius: 12px;
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
            overflow: hidden;
            transform: rotate(var(--rotation, 0deg));
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            cursor: move;
            user-select: none;
        }

        /* Classic Pin Style (default) */
        .template-map .photo-pin.pin-classic {
            border-radius: 12px;
            background: white;
        }

        /* Compass Pin Style */
        .template-map .photo-pin.pin-compass {
            border-radius: 50%;
            background: linear-gradient(45deg, #8d6e63, #a1887f);
            border: 3px solid #5d4037;
            position: relative;
        }

        .template-map .photo-pin.pin-compass::before {
            content: '🧭';
            position: absolute;
            top: -8px;
            right: -8px;
            font-size: 1.2rem;
            background: white;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        }

        .template-map .photo-pin.pin-compass .pin-image {
            border-radius: 50%;
        }

        /* Tag Pin Style */
        .template-map .photo-pin.pin-tag {
            border-radius: 8px 8px 8px 0;
            background: linear-gradient(135deg, #ff7043, #ff5722);
            color: white;
            position: relative;
        }

        .template-map .photo-pin.pin-tag::before {
            content: '';
            position: absolute;
            bottom: -10px;
            left: 0;
            width: 0;
            height: 0;
            border-left: 10px solid #ff5722;
            border-bottom: 10px solid transparent;
        }

        .template-map .photo-pin.pin-tag .pin-info {
            background: linear-gradient(135deg, #ff7043, #ff5722);
            color: white;
        }

        /* Gem Pin Style */
        .template-map .photo-pin.pin-gem {
            border-radius: 0;
            background: linear-gradient(135deg, #9c27b0, #e91e63);
            transform: rotate(var(--rotation, 0deg)) rotate(45deg);
            position: relative;
        }

        .template-map .photo-pin.pin-gem .pin-image {
            transform: rotate(-45deg);
        }

        .template-map .photo-pin.pin-gem .pin-info {
            transform: rotate(-45deg);
            background: linear-gradient(135deg, #9c27b0, #e91e63);
            color: white;
        }

        .template-map .photo-pin.pin-gem::before {
            content: '💎';
            position: absolute;
            top: -15px;
            left: 50%;
            transform: translateX(-50%) rotate(-45deg);
            font-size: 1.5rem;
            text-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
        }

        /* Postcard Pin Style */
        .template-map .photo-pin.pin-postcard {
            border-radius: 4px;
            background: #fff;
            border: 2px solid #d32f2f;
            position: relative;
        }

        .template-map .photo-pin.pin-postcard::before {
            content: '';
            position: absolute;
            top: 8px;
            right: 8px;
            width: 20px;
            height: 15px;
            background: repeating-linear-gradient(
                45deg,
                #d32f2f,
                #d32f2f 2px,
                white 2px,
                white 4px
            );
            border: 1px solid #d32f2f;
        }

        .template-map .photo-pin.pin-postcard::after {
            content: '📮';
            position: absolute;
            bottom: -8px;
            right: -8px;
            font-size: 1.2rem;
            background: white;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        }

        /* Hover effects for different pin styles */
        .template-map .photo-pin:hover {
            z-index: 10;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
        }

        .template-map .photo-pin.pin-classic:hover {
            transform: rotate(var(--rotation, 0deg)) scale(1.05);
        }

        .template-map .photo-pin.pin-compass:hover {
            transform: rotate(var(--rotation, 0deg)) scale(1.05);
            box-shadow: 0 8px 25px rgba(141, 110, 99, 0.3);
        }

        .template-map .photo-pin.pin-tag:hover {
            transform: rotate(var(--rotation, 0deg)) scale(1.05);
            box-shadow: 0 8px 25px rgba(255, 87, 34, 0.3);
        }

        .template-map .photo-pin.pin-gem:hover {
            transform: rotate(var(--rotation, 0deg)) rotate(45deg) scale(1.05);
            box-shadow: 0 8px 25px rgba(156, 39, 176, 0.3);
        }

        .template-map .photo-pin.pin-postcard:hover {
            transform: rotate(var(--rotation, 0deg)) scale(1.05);
            box-shadow: 0 8px 25px rgba(211, 47, 47, 0.3);
        }

        .template-map .photo-pin.dragging {
            z-index: 100;
            box-shadow: 0 12px 30px rgba(0, 0, 0, 0.3);
            cursor: grabbing;
        }

        .template-map .photo-pin.pin-classic.dragging {
            transform: rotate(var(--rotation, 0deg)) scale(1.1);
        }

        .template-map .photo-pin.pin-compass.dragging {
            transform: rotate(var(--rotation, 0deg)) scale(1.1);
        }

        .template-map .photo-pin.pin-tag.dragging {
            transform: rotate(var(--rotation, 0deg)) scale(1.1);
        }

        .template-map .photo-pin.pin-gem.dragging {
            transform: rotate(var(--rotation, 0deg)) rotate(45deg) scale(1.1);
        }

        .template-map .photo-pin.pin-postcard.dragging {
            transform: rotate(var(--rotation, 0deg)) scale(1.1);
        }

        .template-map .pin-image {
            width: 100%;
            height: 100px;
            object-fit: cover;
            pointer-events: none;
        }

        .template-map .pin-image.original {
            height: auto;
            max-height: 120px;
            object-fit: contain;
            background: #f8f9fa;
        }

        .template-map .pin-info {
            padding: 0.6rem;
            background: white;
            pointer-events: none;
        }

        .template-map .pin-location {
            font-size: 0.65rem;
            color: #666;
            margin-bottom: 0.2rem;
            display: flex;
            align-items: center;
            gap: 0.2rem;
        }

        .template-map .pin-mood {
            font-size: 0.7rem;
            color: #333;
            font-weight: 500;
        }

        .template-map .next-route-text {
            position: absolute;
            bottom: 3rem;
            left: 1.5rem;
            color: #d32f2f;
            font-size: 1rem;
            font-weight: 600;
            transform: rotate(-5deg);
            pointer-events: none;
        }

        .template-map .embrace-text {
            position: absolute;
            bottom: 1.5rem;
            right: 1.5rem;
            color: #333;
            font-size: 0.8rem;
            text-align: right;
            line-height: 1.4;
            pointer-events: none;
        }

        /* Template 3: Route */
        .template-route {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            position: relative;
        }

        .template-route .poster-header {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            padding: 2rem;
            text-align: center;
        }

        .template-route .poster-title {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        .template-route .poster-subtitle {
            font-size: 1rem;
            opacity: 0.9;
        }

        .template-route .poster-content {
            padding: 2rem 1.5rem;
            position: relative;
            min-height: 600px;
        }

        .template-route .route-path {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1;
            pointer-events: none;
        }

        .template-route .route-path svg {
            width: 100%;
            height: 100%;
        }

        .template-route .route-point {
            position: absolute;
            z-index: 2;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: move;
            transition: transform 0.3s ease;
        }

        .template-route .route-point.dragging {
            transform: scale(1.1);
            z-index: 100;
            cursor: grabbing;
        }

        .template-route .route-point:hover {
            transform: scale(1.05);
        }

        .template-route .route-flag {
            position: absolute;
            width: 24px;
            height: 24px;
            background: linear-gradient(45deg, #dc3545, #ff6b6b);
            border-radius: 50%;
            border: 2px solid white;
            box-shadow: 0 4px 12px rgba(220, 53, 69, 0.4);
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }

        /* 路径点悬停效果 */
        .template-route .route-point:hover .route-card {
            transform: scale(1.05);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
        }

        /* 添加路径样式选择器 */
        .route-style-selector {
            margin-bottom: 2rem;
            text-align: center;
            display: none;
        }

        .template-route .route-flag::after {
            content: '🚩';
            position: absolute;
            top: -12px;
            left: -6px;
            font-size: 0.9rem;
        }

        .template-route .route-flag.position-top-left {
            top: -10px;
            left: -10px;
        }

        .template-route .route-flag.position-top-right {
            top: -10px;
            right: -10px;
            left: auto;
        }

        .template-route .route-flag.position-bottom-left {
            bottom: -10px;
            left: -10px;
            top: auto;
        }

        .template-route .route-flag.position-bottom-right {
            bottom: -10px;
            right: -10px;
            top: auto;
            left: auto;
        }

        .template-route .route-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            width: 120px;
            transition: transform 0.3s ease;
            pointer-events: none;
        }

        .template-route .route-card:hover {
            transform: scale(1.02);
        }

        .template-route .route-image {
            width: 100%;
            height: 70px;
            object-fit: cover;
        }

        .template-route .route-image.original {
            height: auto;
            max-height: 90px;
            object-fit: contain;
            background: #f8f9fa;
        }

        .template-route .route-info {
            padding: 0.6rem;
        }

        .template-route .route-location {
            font-size: 0.65rem;
            color: #28a745;
            font-weight: 600;
            margin-bottom: 0.2rem;
        }

        .template-route .route-time {
            font-size: 0.55rem;
            color: #6c757d;
        }

        /* Template 4: Collage */
        .template-collage {
            background: #ffffff;
            position: relative;
            overflow: hidden;
        }

        .template-collage .poster-header {
            background: linear-gradient(135deg, #6f42c1, #e83e8c);
            color: white;
            padding: 1.5rem;
            text-align: center;
        }

        .template-collage .poster-title {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        .template-collage .poster-subtitle {
            font-size: 1rem;
            opacity: 0.9;
        }

        .template-collage .poster-content {
            padding: 1rem;
            position: relative;
            min-height: 650px;
        }

        .template-collage .collage-item {
            position: absolute;
            background: white;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
            transition: transform 0.3s ease, z-index 0.3s ease;
            cursor: move;
        }

        .template-collage .collage-item:hover {
            transform: scale(1.05) rotate(var(--hover-rotation, 0deg));
            z-index: 10;
        }

        .template-collage .collage-item.selected {
            border: 3px solid #6f42c1;
            box-shadow: 0 0 0 2px rgba(111, 66, 193, 0.2), 0 8px 25px rgba(0, 0, 0, 0.15);
        }

        .template-collage .collage-item.dragging {
            transform: scale(1.05) rotate(var(--rotation, 0deg));
            z-index: 100;
            cursor: grabbing;
        }

        .template-collage .collage-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .template-collage .collage-image.original {
            object-fit: contain;
            background: #f8f9fa;
        }

        .template-collage .collage-overlay {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
            color: white;
            padding: 0.8rem;
            font-size: 0.7rem;
            text-align: center;
        }

        .template-collage .collage-text {
            font-weight: 500;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 3rem 2rem;
            color: #666;
        }

        .empty-icon {
            font-size: 3rem;
            margin-bottom: 1rem;
            opacity: 0.5;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
                gap: 1rem;
            }
            
            .poster-section {
                position: static;
            }
            
            .upload-section {
                order: 2;
            }

            .template-options {
                flex-direction: column;
                gap: 0.5rem;
            }

            .template-option {
                padding: 0.6rem 1rem;
                font-size: 0.8rem;
            }

            .image-mode-options {
                flex-direction: column;
                gap: 0.5rem;
            }

            .image-mode-option {
                padding: 0.5rem 1rem;
                font-size: 0.8rem;
            }

            .poster-size-options {
                flex-direction: column;
                gap: 0.5rem;
            }

            .poster-size-option {
                padding: 0.5rem 1rem;
                font-size: 0.8rem;
            }
        }

        .template-timeline .photo-moment:nth-child(3n).frame-polaroid {
            --frame-rotation: -0.8deg;
        }

        .template-timeline .moment-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            display: block;
        }

        .template-timeline .moment-image.original {
            height: auto;
            max-height: 300px;
            object-fit: contain;
            background: #f8f9fa;
        }

        .template-timeline .moment-info {
            padding: 1rem;
            background: white;
        }

        .template-timeline .moment-time {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.8rem;
            padding-bottom: 0.5rem;
            border-bottom: 1px solid #e9ecef;
        }

        .template-timeline .time-stamp {
            font-size: 0.8rem;
            color: #6c757d;
            font-weight: 500;
        }

        .template-timeline .location {
            font-size: 0.8rem;
            color: #495057;
            background: #e9ecef;
            padding: 0.2rem 0.6rem;
            border-radius: 8px;
        }

        .template-timeline .mood-indicator {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.9rem;
            color: #495057;
            margin-bottom: 0.8rem;
        }

        .template-timeline .mood-emoji {
            font-size: 1.2rem;
        }

        .template-timeline .moment-thought {
            font-size: 0.9rem;
            color: #333;
            line-height: 1.5;
            font-style: italic;
        }

        /* Pin Style Selector for Map */
        .pin-style-selector {
            margin-bottom: 2rem;
            text-align: center;
            display: none;
        }

        .pin-style-selector h3 {
            font-size: 1.1rem;
            color: #333;
            margin-bottom: 0.8rem;
        }

        .pin-style-options {
            display: flex;
            gap: 0.8rem;
            justify-content: center;
        }

        .pin-style-option {
            padding: 0.6rem 1.2rem;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .pin-style-option.active {
            border-color: #28a745;
            background: #28a745;
            color: white;
        }

        .pin-style-option:hover {
            border-color: #28a745;
            transform: translateY(-1px);
        }

        /* Individual Pin Style Selector */
        .pin-style-popup {
            display: none;
        }

        /* Map Theme Selector */
        .map-theme-selector {
            margin-bottom: 2rem;
            text-align: center;
        }

        .map-theme-selector h3 {
            font-size: 1.1rem;
            color: #333;
            margin-bottom: 0.8rem;
        }

        .map-theme-options {
            display: flex;
            gap: 0.8rem;
            justify-content: center;
        }

        .map-theme-option {
            padding: 0.6rem 1.2rem;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .map-theme-option.active {
            border-color: #17a2b8;
            background: #17a2b8;
            color: white;
        }

        .map-theme-option:hover {
            border-color: #17a2b8;
            transform: translateY(-1px);
        }

        /* Route Style Selector */
        .route-style-selector {
            margin-bottom: 2rem;
            text-align: center;
            display: none;
        }

        .route-style-selector h3 {
            font-size: 1.1rem;
            color: #333;
            margin-bottom: 0.8rem;
        }

        .route-style-options {
            display: flex;
            gap: 0.8rem;
            justify-content: center;
        }

        .route-style-option {
            padding: 0.6rem 1.2rem;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .route-style-option.active {
            border-color: #28a745;
            background: #28a745;
            color: white;
        }

        .route-style-option:hover {
            border-color: #28a745;
            transform: translateY(-1px);
        }

        /* 增强的路径动画效果 */
        .template-route .route-path svg {
            width: 100%;
            height: 100%;
        }

        .template-route .route-path .animated-path {
            stroke-dasharray: 8, 4;
            animation: pathFlow 3s linear infinite;
        }

        @keyframes pathFlow {
            0% { stroke-dashoffset: 0; }
            100% { stroke-dashoffset: 12; }
        }

        .template-route .route-path .glow-path {
            filter: drop-shadow(0 0 8px rgba(40, 167, 69, 0.6));
        }

        /* 自动分配的旗帜位置 */
        .template-route .route-flag {
            position: absolute;
            width: 20px;
            height: 20px;
            background: linear-gradient(45deg, #dc3545, #ff6b6b);
            border-radius: 50%;
            border: 2px solid white;
            box-shadow: 0 4px 12px rgba(220, 53, 69, 0.4);
            animation: flagPulse 2s infinite;
            z-index: 3;
            pointer-events: none;
        }

        @keyframes flagPulse {
            0% { transform: scale(1); box-shadow: 0 4px 12px rgba(220, 53, 69, 0.4); }
            50% { transform: scale(1.2); box-shadow: 0 6px 20px rgba(220, 53, 69, 0.6); }
            100% { transform: scale(1); box-shadow: 0 4px 12px rgba(220, 53, 69, 0.4); }
        }

        .template-route .route-flag::after {
            content: '🚩';
            position: absolute;
            top: -12px;
            left: -6px;
            font-size: 0.9rem;
            animation: flagWave 1.5s ease-in-out infinite;
        }

        @keyframes flagWave {
            0%, 100% { transform: rotate(0deg); }
            25% { transform: rotate(5deg); }
            75% { transform: rotate(-5deg); }
        }
    </style>
</head>
<body>
    <a href="index.html" class="back-btn">← Back to Home</a>
    
    <div class="container">
        <div class="upload-section">
            <h1 class="upload-title">AI Smart Travel Poster</h1>
            <p class="upload-subtitle">Upload your travel photos and let AI create your personalized travel story</p>
            
            <!-- Template Selector -->
            <div class="template-selector">
                <h3>Choose Poster Template</h3>
                <div class="template-options">
                    <div class="template-option active" data-template="timeline">
                        📱 Timeline
                    </div>
                    <div class="template-option" data-template="map">
                        🗺️ Map Pins
                    </div>
                    <div class="template-option" data-template="route">
                        🚩 Route Map
                    </div>
                    <div class="template-option" data-template="collage">
                        🎨 Collage
                    </div>
                </div>
            </div>

            <!-- Image Mode Selector -->
            <div class="image-mode-selector">
                <h3>Image Display Mode</h3>
                <div class="image-mode-options">
                    <div class="image-mode-option active" data-mode="cropped">
                        🔳 Cropped
                    </div>
                    <div class="image-mode-option" data-mode="original">
                        🖼️ Original
                    </div>
                </div>
            </div>

            <!-- Poster Size Selector -->
            <div class="poster-size-selector">
                <h3>Poster Size</h3>
                <div class="poster-size-options">
                    <div class="poster-size-option" data-size="small">
                        📱 Small (360px)
                    </div>
                    <div class="poster-size-option active" data-size="medium">
                        💻 Medium (450px)
                    </div>
                    <div class="poster-size-option" data-size="large">
                        🖥️ Large (600px)
                    </div>
                </div>
            </div>

            <!-- Frame Style Selector for Timeline -->
            <div class="frame-style-selector" id="frameStyleSelector">
                <h3>Frame Style</h3>
                <div class="frame-style-options">
                    <div class="frame-style-option active" data-style="modern">
                        🖼️ Modern
                    </div>
                    <div class="frame-style-option" data-style="polaroid">
                        📸 Polaroid
                    </div>
                    <div class="frame-style-option" data-style="vintage">
                        🎞️ Vintage
                    </div>
                    <div class="frame-style-option" data-style="film">
                        🎬 Film
                    </div>
                    <div class="frame-style-option" data-style="decorative">
                        ✨ Decorative
                    </div>
                </div>
            </div>

            <!-- Collage Controls -->
            <div class="collage-controls" id="collageControls">
                <h3>Collage Controls</h3>
                <div class="collage-control-info">
                    <p>💡 Click on images to select, then adjust position and size</p>
                    <div class="selected-image-info" id="selectedImageInfo">
                        <h4>Selected Image #<span id="selectedImageIndex">1</span></h4>
                        <div class="control-group">
                            <label>Size:</label>
                            <input type="range" id="sizeSlider" min="50" max="200" value="100" step="10">
                            <span id="sizeValue">100%</span>
                        </div>
                        <div class="control-group">
                            <label>Rotation:</label>
                            <input type="range" id="rotationSlider" min="-45" max="45" value="0" step="5">
                            <span id="rotationValue">0°</span>
                        </div>
                        <button id="resetImageBtn" class="control-btn">Reset</button>
                    </div>
                </div>
            </div>
            
            <!-- Pin Style Selector for Map -->
            <div class="pin-style-selector" id="pinStyleSelector">
                <h3>Pin Style</h3>
                <div class="pin-style-options">
                    <div class="pin-style-option active" data-style="classic">
                        📍 Classic
                    </div>
                    <div class="pin-style-option" data-style="compass">
                        🧭 Compass
                    </div>
                    <div class="pin-style-option" data-style="tag">
                        🏷️ Tag
                    </div>
                    <div class="pin-style-option" data-style="gem">
                        💎 Gem
                    </div>
                    <div class="pin-style-option" data-style="postcard">
                        📮 Postcard
                    </div>
                </div>
            </div>

            <!-- Map Theme Selector -->
            <div class="map-theme-selector" id="mapThemeSelector">
                <h3>Map Theme</h3>
                <div class="map-theme-options">
                    <div class="map-theme-option active" data-theme="default">
                        🌍 Default
                    </div>
                    <div class="map-theme-option" data-theme="ocean">
                        🌊 Ocean
                    </div>
                    <div class="map-theme-option" data-theme="forest">
                        🌲 Forest
                    </div>
                    <div class="map-theme-option" data-theme="desert">
                        🏜️ Desert
                    </div>
                    <div class="map-theme-option" data-theme="city">
                        🏙️ City
                    </div>
                </div>
            </div>
            
            <!-- Route Style Selector -->
            <div class="route-style-selector" id="routeStyleSelector">
                <h3>Route Style</h3>
                <div class="route-style-options">
                    <div class="route-style-option active" data-style="curved">
                        🌊 Curved
                    </div>
                    <div class="route-style-option" data-style="zigzag">
                        ⚡ Zigzag
                    </div>
                    <div class="route-style-option" data-style="straight">
                        📏 Straight
                    </div>
                    <div class="route-style-option" data-style="spiral">
                        🌀 Spiral
                    </div>
                </div>
            </div>
            
            <div class="upload-area" onclick="document.getElementById('fileInput').click()">
                <div class="upload-icon">📸</div>
                <div class="upload-text">Click or drag to upload images</div>
                <div class="upload-hint">Supports JPG, PNG formats, max 10 images</div>
            </div>
            
            <input type="file" id="fileInput" multiple accept="image/*">
            
            <div class="uploaded-images" id="uploadedImages"></div>
            
            <button class="analyze-btn" id="analyzeBtn" disabled>
                🤖 AI Smart Analysis
            </button>

            <button class="download-btn" id="downloadBtn">
                📥 Download Poster（test）
            </button>
            
            <div class="loading" id="loading">
                <div class="spinner"></div>
                <p>AI is analyzing your photos...</p>
            </div>

        </div>
        
        <div class="poster-section">
            <div class="poster" id="poster">
                <div class="poster-header">
                    <h1 class="poster-title">My Travel Story</h1>
                    <p class="poster-subtitle">AI-Generated Personal Memories</p>
                </div>
                
                <div class="poster-content" id="posterContent">
                    <div class="empty-state">
                        <div class="empty-icon">🌟</div>
                        <p>Upload photos and AI will generate<br>your beautiful travel poster</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let uploadedFiles = [];
        let currentTemplate = 'timeline';
        let imageMode = 'cropped';
        let posterSize = 'medium';
        let selectedCollageItem = null;
        let frameStyle = 'modern';
        let pinStyle = 'classic';
        let mapTheme = 'default';
        const maxFiles = 10;
        let draggedElement = null;
        let dragOffset = { x: 0, y: 0 };
        let routeStyle = 'curved';
        
        // Mock AI analysis data
        const mockAnalysisData = {
            locations: ['Times Square NYC', 'Golden Gate Bridge', 'Central Park', 'Hollywood Sign', 'Statue of Liberty', 'Miami Beach', 'Grand Canyon', 'Yellowstone', 'Niagara Falls', 'Las Vegas Strip'],
            moods: [
                { emoji: '😊', text: 'Happy', color: '#28a745' },
                { emoji: '🤩', text: 'Excited', color: '#fd7e14' },
                { emoji: '🧘', text: 'Peaceful', color: '#20c997' },
                { emoji: '🌸', text: 'Nostalgic', color: '#6f42c1' },
                { emoji: '🏃', text: 'Adventurous', color: '#dc3545' },
                { emoji: '🤔', text: 'Thoughtful', color: '#6c757d' },
                { emoji: '❤️', text: 'Moved', color: '#e83e8c' },
                { emoji: '🎉', text: 'Celebratory', color: '#ffc107' }
            ],
            thoughts: [
                'This moment of beauty deserves to be treasured forever',
                'The meaning of travel is not the destination, but the scenery along the way',
                'Every departure is to meet a better self',
                'The world is so big, I want to see it and record it',
                'Some scenery can only be appreciated when you see it with your own eyes',
                'Travel teaches me not only to appreciate beauty, but also to feel life',
                'Every day on the road is a redefinition of life',
                'Everything here makes me feel novel and excited',
                'Calm down and feel the unique charm of this place',
                'May this beautiful memory always accompany me',
                'Behind every photo is a story worth savoring',
                'Travel makes me understand that the world is more wonderful than imagined'
            ]
        };

        // Poster size switching
        document.querySelectorAll('.poster-size-option').forEach(option => {
            option.addEventListener('click', function() {
                document.querySelectorAll('.poster-size-option').forEach(opt => opt.classList.remove('active'));
                this.classList.add('active');
                posterSize = this.dataset.size;
                
                updatePosterSize();
                
                if (uploadedFiles.length > 0) {
                    generatePoster();
                }
            });
        });

        function updatePosterSize() {
            const poster = document.getElementById('poster');
            poster.classList.remove('size-small', 'size-medium', 'size-large');
            poster.classList.add(`size-${posterSize}`);
        }

        // Template switching
        document.querySelectorAll('.template-option').forEach(option => {
            option.addEventListener('click', function() {
                document.querySelectorAll('.template-option').forEach(opt => opt.classList.remove('active'));
                this.classList.add('active');
                currentTemplate = this.dataset.template;
                
                updateControlPanels();
                
                if (uploadedFiles.length > 0) {
                    generatePoster();
                }
            });
        });

        function updateControlPanels() {
            const collageControls = document.getElementById('collageControls');
            const frameStyleSelector = document.getElementById('frameStyleSelector');
            const pinStyleSelector = document.getElementById('pinStyleSelector');
            const mapThemeSelector = document.getElementById('mapThemeSelector');
            const routeStyleSelector = document.getElementById('routeStyleSelector');
            
            if (currentTemplate === 'timeline') {
                collageControls.style.display = 'none';
                frameStyleSelector.style.display = 'block';
                pinStyleSelector.style.display = 'none';
                mapThemeSelector.style.display = 'none';
                routeStyleSelector.style.display = 'none';
            } else if (currentTemplate === 'map') {
                collageControls.style.display = 'none';
                frameStyleSelector.style.display = 'none';
                pinStyleSelector.style.display = 'none';
                mapThemeSelector.style.display = 'block';
                routeStyleSelector.style.display = 'none';
            } else if (currentTemplate === 'route') {
                collageControls.style.display = 'none';
                frameStyleSelector.style.display = 'none';
                pinStyleSelector.style.display = 'none';
                mapThemeSelector.style.display = 'none';
                routeStyleSelector.style.display = 'block';
            } else if (currentTemplate === 'collage') {
                collageControls.style.display = 'block';
                frameStyleSelector.style.display = 'none';
                pinStyleSelector.style.display = 'none';
                mapThemeSelector.style.display = 'none';
                routeStyleSelector.style.display = 'none';
            } else {
                collageControls.style.display = 'none';
                frameStyleSelector.style.display = 'none';
                pinStyleSelector.style.display = 'none';
                mapThemeSelector.style.display = 'none';
                routeStyleSelector.style.display = 'none';
            }
        }

        // Image mode switching
        document.querySelectorAll('.image-mode-option').forEach(option => {
            option.addEventListener('click', function() {
                document.querySelectorAll('.image-mode-option').forEach(opt => opt.classList.remove('active'));
                this.classList.add('active');
                imageMode = this.dataset.mode;
                
                if (uploadedFiles.length > 0) {
                    generatePoster();
                }
            });
        });

        // Frame style switching for timeline
        document.querySelectorAll('.frame-style-option').forEach(option => {
            option.addEventListener('click', function() {
                document.querySelectorAll('.frame-style-option').forEach(opt => opt.classList.remove('active'));
                this.classList.add('active');
                frameStyle = this.dataset.style;
                
                if (uploadedFiles.length > 0 && currentTemplate === 'timeline') {
                    generatePoster();
                }
            });
        });

        // Collage controls
        const sizeSlider = document.getElementById('sizeSlider');
        const rotationSlider = document.getElementById('rotationSlider');
        const sizeValue = document.getElementById('sizeValue');
        const rotationValue = document.getElementById('rotationValue');
        const resetImageBtn = document.getElementById('resetImageBtn');

        sizeSlider.addEventListener('input', function() {
            const value = this.value;
            sizeValue.textContent = value + '%';
            if (selectedCollageItem) {
                const scale = value / 100;
                updateSelectedItemTransform(scale);
            }
        });

        rotationSlider.addEventListener('input', function() {
            const value = this.value;
            rotationValue.textContent = value + '°';
            if (selectedCollageItem) {
                selectedCollageItem.style.setProperty('--rotation', value + 'deg');
                updateSelectedItemTransform();
            }
        });

        resetImageBtn.addEventListener('click', function() {
            if (selectedCollageItem) {
                selectedCollageItem.style.transform = 'rotate(0deg) scale(1)';
                selectedCollageItem.style.setProperty('--rotation', '0deg');
                sizeSlider.value = 100;
                rotationSlider.value = 0;
                sizeValue.textContent = '100%';
                rotationValue.textContent = '0°';
            }
        });

        function updateSelectedItemTransform(scale) {
            if (!selectedCollageItem) return;
            
            const currentScale = scale || (sizeSlider.value / 100);
            const currentRotation = rotationSlider.value;
            
            selectedCollageItem.style.transform = `rotate(${currentRotation}deg) scale(${currentScale})`;
        }

        // File upload handling
        const fileInput = document.getElementById('fileInput');
        const uploadedImages = document.getElementById('uploadedImages');
        const analyzeBtn = document.getElementById('analyzeBtn');
        const downloadBtn = document.getElementById('downloadBtn');
        const uploadArea = document.querySelector('.upload-area');

        fileInput.addEventListener('change', handleFileSelect);
        uploadArea.addEventListener('dragover', handleDragOver);
        uploadArea.addEventListener('drop', handleDrop);
        analyzeBtn.addEventListener('click', analyzeImages);
        downloadBtn.addEventListener('click', downloadPoster);

        function handleFileSelect(e) {
            const files = Array.from(e.target.files);
            addFiles(files);
        }

        function handleDragOver(e) {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        }

        function handleDrop(e) {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const files = Array.from(e.dataTransfer.files);
            addFiles(files);
        }

        function addFiles(files) {
            const imageFiles = files.filter(file => file.type.startsWith('image/'));
            
            if (uploadedFiles.length + imageFiles.length > maxFiles) {
                alert(`Maximum ${maxFiles} images allowed`);
                return;
            }

            imageFiles.forEach(file => {
                if (uploadedFiles.length < maxFiles) {
                    uploadedFiles.push(file);
                    displayImage(file, uploadedFiles.length - 1);
                }
            });

            updateAnalyzeButton();
        }

        function displayImage(file, index) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const imagePreview = document.createElement('div');
                imagePreview.className = 'image-preview';
                imagePreview.innerHTML = `
                    <img src="${e.target.result}" alt="Preview">
                    <button class="remove-image" onclick="removeImage(${index})">×</button>
                `;
                uploadedImages.appendChild(imagePreview);
            };
            reader.readAsDataURL(file);
        }

        function removeImage(index) {
            uploadedFiles.splice(index, 1);
            refreshImagePreviews();
            updateAnalyzeButton();
            
            if (document.querySelector('.download-btn').classList.contains('show')) {
                generatePoster();
            }
        }

        function refreshImagePreviews() {
            uploadedImages.innerHTML = '';
            uploadedFiles.forEach((file, index) => {
                displayImage(file, index);
            });
        }

        function updateAnalyzeButton() {
            analyzeBtn.disabled = uploadedFiles.length === 0;
            if (uploadedFiles.length > 0) {
                analyzeBtn.textContent = `🤖 AI Smart Analysis (${uploadedFiles.length} images)`;
            } else {
                analyzeBtn.textContent = '🤖 AI Smart Analysis';
            }
        }

        function analyzeImages() {
            const loading = document.getElementById('loading');
            
            loading.classList.add('active');
            analyzeBtn.disabled = true;
            
            setTimeout(() => {
                loading.classList.remove('active');
                generatePoster();
                analyzeBtn.disabled = false;
                downloadBtn.classList.add('show');
            }, 3000);
        }

        function generatePoster() {
            const poster = document.getElementById('poster');
            
            poster.classList.remove('template-timeline', 'template-map', 'template-route', 'template-collage');
            poster.classList.add(`template-${currentTemplate}`);
            
            if (currentTemplate === 'timeline') {
                generateTimelinePoster();
            } else if (currentTemplate === 'map') {
                generateMapPoster();
            } else if (currentTemplate === 'route') {
                generateRoutePoster();
            } else if (currentTemplate === 'collage') {
                generateCollagePoster();
            }
        }

        function generateTimelinePoster() {
            const posterContent = document.getElementById('posterContent');
            let html = '';
            let processedCount = 0;
            
            uploadedFiles.forEach((file, index) => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const location = mockAnalysisData.locations[Math.floor(Math.random() * mockAnalysisData.locations.length)];
                    const mood = mockAnalysisData.moods[Math.floor(Math.random() * mockAnalysisData.moods.length)];
                    const thought = mockAnalysisData.thoughts[Math.floor(Math.random() * mockAnalysisData.thoughts.length)];
                    
                    const date = new Date();
                    date.setDate(date.getDate() - Math.floor(Math.random() * 30));
                    const timeString = `${date.getMonth() + 1}/${date.getDate()} ${String(Math.floor(Math.random() * 24)).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}`;
                    
                    const momentHtml = `
                        <div class="photo-moment frame-${frameStyle}">
                            <img src="${e.target.result}" alt="Travel photo" class="moment-image ${imageMode}">
                            <div class="moment-info">
                                <div class="moment-time">
                                    <span class="time-stamp">${timeString}</span>
                                    <span class="location">📍 ${location}</span>
                                </div>
                                <div class="mood-indicator" style="color: ${mood.color}">
                                    <span class="mood-emoji">${mood.emoji}</span>
                                    <span>${mood.text}</span>
                                </div>
                                <p class="moment-thought">${thought}</p>
                            </div>
                        </div>
                    `;
                    
                    html += momentHtml;
                    processedCount++;
                    
                    if (processedCount === uploadedFiles.length) {
                        posterContent.innerHTML = html;
                    }
                };
                reader.readAsDataURL(file);
            });
        }

        function generateMapPoster() {
            const posterContent = document.getElementById('posterContent');
            const poster = document.getElementById('poster');
            
            // Apply map theme
            poster.classList.remove('theme-default', 'theme-ocean', 'theme-forest', 'theme-desert', 'theme-city');
            poster.classList.add(`theme-${mapTheme}`);
            
            const posterTitle = document.querySelector('.poster-title');
            const posterSubtitle = document.querySelector('.poster-subtitle');
            posterTitle.textContent = 'Route';
            posterSubtitle.textContent = 'Connecting You to the Heart of Nature';
            
            let html = `
                <div class="map-background"></div>
                <div class="next-route-text">Next ✈️<br>➡️ Route</div>
                <div class="embrace-text">Embrace the Journey,<br>Discover the Wilderness.</div>
            `;
            
            const positions = generateNonOverlappingPositions(uploadedFiles.length);
            
            let processedCount = 0;
            
            uploadedFiles.forEach((file, index) => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const location = mockAnalysisData.locations[Math.floor(Math.random() * mockAnalysisData.locations.length)];
                    const mood = mockAnalysisData.moods[Math.floor(Math.random() * mockAnalysisData.moods.length)];
                    const pos = positions[index];
                    
                    const pinHtml = `
                        <div class="photo-pin pin-classic draggable-pin" data-index="${index}" style="
                            top: ${pos.top}px; 
                            left: ${pos.left}px; 
                            --rotation: ${pos.rotation}deg;
                            width: ${pos.width}px;
                        ">
                            <img src="${e.target.result}" alt="Travel photo" class="pin-image ${imageMode}">
                            <div class="pin-info">
                                <div class="pin-location">📍 ${location}</div>
                                <div class="pin-mood">${mood.emoji} ${mood.text}</div>
                            </div>
                        </div>
                    `;
                    
                    html += pinHtml;
                    processedCount++;
                    
                    if (processedCount === uploadedFiles.length) {
                        posterContent.innerHTML = html;
                        initializeDragFunctionality();
                    }
                };
                reader.readAsDataURL(file);
            });
        }

        function generateRoutePoster() {
            const posterContent = document.getElementById('posterContent');
            
            const posterTitle = document.querySelector('.poster-title');
            const posterSubtitle = document.querySelector('.poster-subtitle');
            posterTitle.textContent = 'My Travel Route';
            posterSubtitle.textContent = 'Every stop is a beautiful memory';
            
            const pathSvg = generateSnakePath();
            
            let html = `<div class="route-path">${pathSvg}</div>`;
            let processedCount = 0;
            
            const routePositions = generateRoutePositions(uploadedFiles.length);
            
            uploadedFiles.forEach((file, index) => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const location = mockAnalysisData.locations[Math.floor(Math.random() * mockAnalysisData.locations.length)];
                    
                    const date = new Date();
                    date.setDate(date.getDate() - (uploadedFiles.length - index));
                    const timeString = `${date.getMonth() + 1}/${date.getDate()}`;
                    
                    const pos = routePositions[index];
                    
                    const pointHtml = `
                        <div class="route-point draggable-route-point" data-index="${index}" style="
                            top: ${pos.y}px;
                            left: ${pos.x}px;
                        ">
                            <div class="route-flag"></div>
                            <div class="route-card">
                                <img src="${e.target.result}" alt="Travel photo" class="route-image ${imageMode}">
                                <div class="route-info">
                                    <div class="route-location">${location}</div>
                                    <div class="route-time">${timeString}</div>
                                </div>
                            </div>
                        </div>
                    `;
                    
                    html += pointHtml;
                    processedCount++;
                    
                    if (processedCount === uploadedFiles.length) {
                        posterContent.innerHTML = html;
                        initializeRouteDragFunctionality();
                    }
                };
                reader.readAsDataURL(file);
            });
        }

        function generateCollagePoster() {
            const posterContent = document.getElementById('posterContent');
            
            const posterTitle = document.querySelector('.poster-title');
            const posterSubtitle = document.querySelector('.poster-subtitle');
            posterTitle.textContent = 'Travel Collage';
            posterSubtitle.textContent = 'Every piece is a unique memory';
            
            let html = '';
            let processedCount = 0;
            
            const collagePositions = generateCollagePositions(uploadedFiles.length);
            
            uploadedFiles.forEach((file, index) => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const thought = mockAnalysisData.thoughts[Math.floor(Math.random() * mockAnalysisData.thoughts.length)];
                    const pos = collagePositions[index];
                    
                    const itemHtml = `
                        <div class="collage-item draggable" data-index="${index}" style="
                            top: ${pos.top}px;
                            left: ${pos.left}px;
                            width: ${pos.width}px;
                            height: ${pos.height}px;
                            transform: rotate(${pos.rotation}deg);
                            --rotation: ${pos.rotation}deg;
                            --hover-rotation: ${pos.rotation + 5}deg;
                            border-radius: ${pos.borderRadius};
                            z-index: ${pos.zIndex};
                        ">
                            <img src="${e.target.result}" alt="Travel photo" class="collage-image ${imageMode}">
                            <div class="collage-overlay">
                                <div class="collage-text">${thought.substring(0, 20)}...</div>
                            </div>
                        </div>
                    `;
                    
                    html += itemHtml;
                    processedCount++;
                    
                    if (processedCount === uploadedFiles.length) {
                        posterContent.innerHTML = html;
                        initializeCollageDragFunctionality();
                    }
                };
                reader.readAsDataURL(file);
            });
        }

        // Helper functions
        function generateNonOverlappingPositions(count) {
            const positions = [];
            let posterRect, pinSize;
            
            switch(posterSize) {
                case 'small':
                    posterRect = { width: 360, height: 640 };
                    pinSize = { width: 85, height: 120 };
                    break;
                case 'large':
                    posterRect = { width: 600, height: 1000 };
                    pinSize = { width: 120, height: 170 };
                    break;
                default:
                    posterRect = { width: 450, height: 800 };
                    pinSize = { width: 100, height: 140 };
            }
            
            // 减少可用区域，确保图钉不会超出边界
            const margin = 40;
            const availableWidth = posterRect.width - pinSize.width - margin * 2;
            const availableHeight = posterRect.height - pinSize.height - margin * 2 - 100; // 减去头部高度
            
            for (let i = 0; i < count; i++) {
                let attempts = 0;
                let position;
                
                do {
                    position = {
                        top: Math.random() * availableHeight + 120, // 从头部下方开始
                        left: Math.random() * availableWidth + margin,
                        rotation: (Math.random() - 0.5) * 20,
                        width: pinSize.width - 10 + Math.random() * 20
                    };
                    attempts++;
                } while (isOverlapping(position, positions, pinSize, margin) && attempts < 50);
                
                positions.push(position);
            }
            
            return positions;
        }

        function isOverlapping(newPos, existingPositions, size, margin) {
            for (let pos of existingPositions) {
                const dx = Math.abs(newPos.left - pos.left);
                const dy = Math.abs(newPos.top - pos.top);
                
                if (dx < size.width + margin && dy < size.height + margin) {
                    return true;
                }
            }
            return false;
        }

        function generateRoutePositions(count) {
            const positions = [];
            let posterRect;
            
            switch(posterSize) {
                case 'small':
                    posterRect = { width: 360, height: 640 };
                    break;
                case 'large':
                    posterRect = { width: 600, height: 1000 };
                    break;
                default:
                    posterRect = { width: 450, height: 800 };
            }
            
            const margin = 60;
            const availableHeight = posterRect.height - 2 * margin - 100; // 减去头部空间
            const availableWidth = posterRect.width - 2 * margin - 120;
            
            if (routeStyle === 'curved') {
                // 曲线布局 - 左右交替
                const stepY = availableHeight / Math.max(count - 1, 1);
                for (let i = 0; i < count; i++) {
                    const y = margin + 100 + i * stepY; // 从头部下方开始
                    const x = margin + (i % 2) * availableWidth;
                    positions.push({ x, y });
                }
            } else if (routeStyle === 'zigzag') {
                // 锯齿状布局 - 三列交替
                const stepY = availableHeight / Math.max(count - 1, 1);
                for (let i = 0; i < count; i++) {
                    const y = margin + 100 + i * stepY;
                    const x = margin + (i % 3) * (availableWidth / 2);
                    positions.push({ x, y });
                }
            } else if (routeStyle === 'straight') {
                // 直线布局 - 中间垂直排列
                const stepY = availableHeight / Math.max(count - 1, 1);
                const centerX = margin + availableWidth / 2;
                for (let i = 0; i < count; i++) {
                    const y = margin + 100 + i * stepY;
                    const x = centerX + (Math.random() - 0.5) * 60; // 轻微随机偏移
                    positions.push({ x, y });
                }
            } else if (routeStyle === 'spiral') {
                // 螺旋布局
                const centerX = posterRect.width / 2 - 60;
                const centerY = posterRect.height / 2;
                const maxRadius = Math.min(availableWidth, availableHeight) / 3;
                
                for (let i = 0; i < count; i++) {
                    const angle = (i / Math.max(count - 1, 1)) * 4 * Math.PI;
                    const radius = maxRadius * (i / Math.max(count - 1, 1));
                    const x = centerX + radius * Math.cos(angle);
                    const y = centerY + radius * Math.sin(angle);
                    positions.push({ x, y });
                }
            }
            
            return positions;
        }

        function generateSnakePath() {
            const positions = generateRoutePositions(uploadedFiles.length);
            if (positions.length < 2) return '<svg></svg>';
            
            // 根据poster size获取正确的尺寸
            let posterRect;
            switch(posterSize) {
                case 'small':
                    posterRect = { width: 360, height: 640 };
                    break;
                case 'large':
                    posterRect = { width: 600, height: 1000 };
                    break;
                default:
                    posterRect = { width: 450, height: 800 };
            }
            
            let pathData = '';
            let arrowMarkers = '';
            
            // 调整路径点的偏移量，确保路径连接到卡片中心
            const cardCenterOffsetX = 60; // 卡片宽度的一半
            const cardCenterOffsetY = 35; // 卡片高度的一半
            
            if (routeStyle === 'curved') {
                pathData = `M ${positions[0].x + cardCenterOffsetX} ${positions[0].y + cardCenterOffsetY}`;
                for (let i = 1; i < positions.length; i++) {
                    const prev = positions[i - 1];
                    const curr = positions[i];
                    
                    // 计算控制点，创建更自然的曲线
                    const controlX = (prev.x + curr.x) / 2 + cardCenterOffsetX;
                    const controlY = (prev.y + curr.y) / 2 + cardCenterOffsetY;
                    
                    // 添加一些随机性让曲线更自然
                    const randomOffsetX = (Math.random() - 0.5) * 30;
                    const randomOffsetY = (Math.random() - 0.5) * 30;
                    
                    pathData += ` Q ${controlX + randomOffsetX} ${controlY + randomOffsetY} ${curr.x + cardCenterOffsetX} ${curr.y + cardCenterOffsetY}`;
                }
            } else if (routeStyle === 'zigzag') {
                pathData = `M ${positions[0].x + cardCenterOffsetX} ${positions[0].y + cardCenterOffsetY}`;
                for (let i = 1; i < positions.length; i++) {
                    const curr = positions[i];
                    pathData += ` L ${curr.x + cardCenterOffsetX} ${curr.y + cardCenterOffsetY}`;
                }
            } else if (routeStyle === 'straight') {
                pathData = `M ${positions[0].x + cardCenterOffsetX} ${positions[0].y + cardCenterOffsetY}`;
                for (let i = 1; i < positions.length; i++) {
                    const curr = positions[i];
                    pathData += ` L ${curr.x + cardCenterOffsetX} ${curr.y + cardCenterOffsetY}`;
                }
            } else if (routeStyle === 'spiral') {
                pathData = `M ${positions[0].x + cardCenterOffsetX} ${positions[0].y + cardCenterOffsetY}`;
                for (let i = 1; i < positions.length; i++) {
                    const curr = positions[i];
                    pathData += ` L ${curr.x + cardCenterOffsetX} ${curr.y + cardCenterOffsetY}`;
                }
            }
            
            // 生成方向箭头
            for (let i = 1; i < positions.length; i++) {
                const prev = positions[i - 1];
                const curr = positions[i];
                const midX = (prev.x + curr.x) / 2 + cardCenterOffsetX;
                const midY = (prev.y + curr.y) / 2 + cardCenterOffsetY;
                const angle = Math.atan2(curr.y - prev.y, curr.x - prev.x) * 180 / Math.PI;
                
                arrowMarkers += `<polygon points="0,0 -8,4 -8,-4" fill="#28a745" 
                                transform="translate(${midX},${midY}) rotate(${angle})" 
                                opacity="0.8">
                                <animateTransform attributeName="transform" 
                                                type="rotate" 
                                                values="${angle} ${midX} ${midY}; ${angle + 10} ${midX} ${midY}; ${angle} ${midX} ${midY}" 
                                                dur="2s" 
                                                repeatCount="indefinite"/>
                                </polygon>`;
            }
            
            // 根据poster size调整stroke-width
            let strokeWidth;
            switch(posterSize) {
                case 'small':
                    strokeWidth = 3;
                    break;
                case 'large':
                    strokeWidth = 5;
                    break;
                default:
                    strokeWidth = 4;
            }
            
            return `<svg viewBox="0 0 ${posterRect.width} ${posterRect.height}" style="width: 100%; height: 100%;">
                <defs>
                    <filter id="glow">
                        <feGaussianBlur stdDeviation="3" result="coloredBlur"/>
                        <feMerge>
                            <feMergeNode in="coloredBlur"/>
                            <feMergeNode in="SourceGraphic"/>
                        </feMerge>
                    </filter>
                    <linearGradient id="pathGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                        <stop offset="0%" style="stop-color:#28a745;stop-opacity:1" />
                        <stop offset="50%" style="stop-color:#20c997;stop-opacity:1" />
                        <stop offset="100%" style="stop-color:#17a2b8;stop-opacity:1" />
                    </linearGradient>
                </defs>
                <path d="${pathData}" stroke="url(#pathGradient)" stroke-width="${strokeWidth}" fill="none" 
                      class="animated-path glow-path" filter="url(#glow)"/>
                ${arrowMarkers}
            </svg>`;
        }

        function generateCollagePositions(count) {
            const positions = [];
            let posterRect, baseSize;
            
            switch(posterSize) {
                case 'small':
                    posterRect = { width: 360, height: 640 };
                    baseSize = { width: 80, height: 80 };
                    break;
                case 'large':
                    posterRect = { width: 600, height: 1000 };
                    baseSize = { width: 140, height: 140 };
                    break;
                default:
                    posterRect = { width: 450, height: 800 };
                    baseSize = { width: 110, height: 110 };
            }
            
            const shapes = [
                { borderRadius: '50%', widthRatio: 1, heightRatio: 1 },
                { borderRadius: '20px', widthRatio: 1.2, heightRatio: 0.8 },
                { borderRadius: '20px', widthRatio: 0.8, heightRatio: 1.2 },
                { borderRadius: '20px 50px', widthRatio: 1, heightRatio: 1 },
                { borderRadius: '50% 20px 50% 20px', widthRatio: 1, heightRatio: 1 },
            ];
            
            for (let i = 0; i < count; i++) {
                const shape = shapes[i % shapes.length];
                let attempts = 0;
                let position;
                
                do {
                    position = {
                        top: Math.random() * (posterRect.height - baseSize.height * shape.heightRatio - 40) + 20,
                        left: Math.random() * (posterRect.width - baseSize.width * shape.widthRatio - 40) + 20,
                        width: baseSize.width * shape.widthRatio,
                        height: baseSize.height * shape.heightRatio,
                        rotation: (Math.random() - 0.5) * 30,
                        borderRadius: shape.borderRadius,
                        zIndex: Math.floor(Math.random() * 5) + 1
                    };
                    attempts++;
                } while (isCollageOverlapping(position, positions, 15) && attempts < 50);
                
                positions.push(position);
            }
            
            return positions;
        }

        function isCollageOverlapping(newPos, existingPositions, margin) {
            for (let pos of existingPositions) {
                const dx = Math.abs(newPos.left - pos.left);
                const dy = Math.abs(newPos.top - pos.top);
                
                if (dx < (newPos.width + pos.width) / 2 + margin && 
                    dy < (newPos.height + pos.height) / 2 + margin) {
                    return true;
                }
            }
            return false;
        }

        // Drag functionality
        function initializeDragFunctionality() {
            const draggablePins = document.querySelectorAll('.draggable-pin');
            
            draggablePins.forEach(pin => {
                pin.addEventListener('mousedown', handleMouseDown);
                pin.addEventListener('touchstart', handleTouchStart, { passive: false });
            });
        }

        function initializeRouteDragFunctionality() {
            const draggablePoints = document.querySelectorAll('.draggable-route-point');
            
            draggablePoints.forEach(point => {
                point.addEventListener('mousedown', handleMouseDown);
                point.addEventListener('touchstart', handleTouchStart, { passive: false });
            });
        }

        function initializeCollageDragFunctionality() {
            const draggableItems = document.querySelectorAll('.collage-item');
            
            draggableItems.forEach(item => {
                item.addEventListener('mousedown', handleMouseDown);
                item.addEventListener('touchstart', handleTouchStart, { passive: false });
                item.addEventListener('click', function(e) {
                    if (currentTemplate === 'collage') {
                        e.stopPropagation();
                        selectCollageItem(this, parseInt(this.dataset.index));
                    }
                });
            });
        }

        function selectCollageItem(item, index) {
            document.querySelectorAll('.collage-item').forEach(el => el.classList.remove('selected'));
            
            item.classList.add('selected');
            selectedCollageItem = item;
            
            const selectedImageInfo = document.getElementById('selectedImageInfo');
            const selectedImageIndex = document.getElementById('selectedImageIndex');
            selectedImageInfo.style.display = 'block';
            selectedImageIndex.textContent = index + 1;
            
            const transform = item.style.transform;
            let currentScale = 1;
            let currentRotation = 0;
            
            if (transform) {
                const scaleMatch = transform.match(/scale\(([^)]+)\)/);
                const rotateMatch = transform.match(/rotate\(([^)]+)\)/);
                
                if (scaleMatch) {
                    currentScale = parseFloat(scaleMatch[1]);
                }
                if (rotateMatch) {
                    currentRotation = parseFloat(rotateMatch[1]);
                }
            }
            
            sizeSlider.value = Math.round(currentScale * 100);
            rotationSlider.value = currentRotation;
            sizeValue.textContent = Math.round(currentScale * 100) + '%';
            rotationValue.textContent = currentRotation + '°';
        }

        function handleMouseDown(e) {
            e.preventDefault();
            startDrag(e, e.clientX, e.clientY);
        }

        function handleTouchStart(e) {
            e.preventDefault();
            const touch = e.touches[0];
            startDrag(e, touch.clientX, touch.clientY);
        }

        function startDrag(e, clientX, clientY) {
            draggedElement = e.target.closest('.photo-pin, .route-point, .collage-item');
            if (!draggedElement) return;

            const rect = draggedElement.getBoundingClientRect();
            dragOffset.x = clientX - rect.left;
            dragOffset.y = clientY - rect.top;

            draggedElement.classList.add('dragging');

            document.addEventListener('mousemove', handleMouseMove);
            document.addEventListener('mouseup', handleMouseUp);
            document.addEventListener('touchmove', handleTouchMove, { passive: false });
            document.addEventListener('touchend', handleTouchEnd);
        }

        function handleMouseMove(e) {
            if (!draggedElement) return;
            updateDragPosition(e.clientX, e.clientY);
        }

        function handleTouchMove(e) {
            if (!draggedElement) return;
            e.preventDefault();
            const touch = e.touches[0];
            updateDragPosition(touch.clientX, touch.clientY);
        }

        function updateDragPosition(clientX, clientY) {
            const posterContent = document.getElementById('posterContent');
            const posterRect = posterContent.getBoundingClientRect();
            
            const newX = clientX - posterRect.left - dragOffset.x;
            const newY = clientY - posterRect.top - dragOffset.y;
            
            // 获取拖拽元素的实际尺寸
            const elementRect = draggedElement.getBoundingClientRect();
            const elementWidth = elementRect.width;
            const elementHeight = elementRect.height;
            
            // 设置边界约束，确保图钉不会超出地图区域
            const margin = 10;
            const maxX = posterRect.width - elementWidth - margin;
            const maxY = posterRect.height - elementHeight - margin;
            const minX = margin;
            const minY = 100; // 避免与标题重叠
            
            const constrainedX = Math.max(minX, Math.min(newX, maxX));
            const constrainedY = Math.max(minY, Math.min(newY, maxY));
            
            draggedElement.style.left = constrainedX + 'px';
            draggedElement.style.top = constrainedY + 'px';
        }

        function handleMouseUp() {
            endDrag();
        }

        function handleTouchEnd() {
            endDrag();
        }

        function endDrag() {
            if (draggedElement) {
                draggedElement.classList.remove('dragging');
                draggedElement = null;
            }

            document.removeEventListener('mousemove', handleMouseMove);
            document.removeEventListener('mouseup', handleMouseUp);
            document.removeEventListener('touchmove', handleTouchMove);
            document.removeEventListener('touchend', handleTouchEnd);
        }

        // Download functionality
        function downloadPoster() {
            const poster = document.getElementById('poster');
            const downloadBtn = document.getElementById('downloadBtn');
            
            downloadBtn.classList.add('downloading');
            downloadBtn.textContent = '🎨 Generating poster...';
            
            // Remove interactive states temporarily
            const selectedItems = document.querySelectorAll('.collage-item.selected');
            selectedItems.forEach(item => {
                item.classList.remove('selected');
                item.dataset.wasSelected = 'true';
            });
            
            // Use html2canvas to capture the poster
            html2canvas(poster, {
                scale: 2,
                useCORS: true,
                allowTaint: true,
                backgroundColor: '#ffffff'
            }).then(canvas => {
                const dataURL = canvas.toDataURL('image/png', 1.0);
                const link = document.createElement('a');
                const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-');
                const templateName = getTemplateDisplayName(currentTemplate);
                const filename = `ATP-${templateName}-${timestamp}.png`;
                
                link.href = dataURL;
                link.download = filename;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                downloadBtn.classList.remove('downloading');
                downloadBtn.classList.add('download-success');
                downloadBtn.textContent = '✅ Download Success!';
                
                setTimeout(() => {
                    downloadBtn.classList.remove('download-success');
                    downloadBtn.textContent = '📥 Download Poster';
                }, 2000);
                
                // Restore interactive states
                document.querySelectorAll('[data-was-selected="true"]').forEach(item => {
                    item.classList.add('selected');
                    item.removeAttribute('data-was-selected');
                });
                
            }).catch(error => {
                console.error('Download failed:', error);
                downloadBtn.classList.remove('downloading');
                downloadBtn.textContent = '❌ Download failed, please try again';
                
                setTimeout(() => {
                    downloadBtn.textContent = '📥 Download Poster';
                }, 3000);
            });
        }

        function getTemplateDisplayName(template) {
            const templateNames = {
                'timeline': 'Timeline',
                'map': 'MapPins',
                'route': 'RouteMap',
                'collage': 'Collage'
            };
            return templateNames[template] || template;
        }

        // Initialize
        updatePosterSize();
        updateControlPanels();

        // Pin style switching for map
        document.querySelectorAll('.pin-style-option').forEach(option => {
            option.addEventListener('click', function() {
                document.querySelectorAll('.pin-style-option').forEach(opt => opt.classList.remove('active'));
                this.classList.add('active');
                pinStyle = this.dataset.style;
                
                if (uploadedFiles.length > 0 && currentTemplate === 'map') {
                    generatePoster();
                }
            });
        });

        // Map theme switching
        document.querySelectorAll('.map-theme-option').forEach(option => {
            option.addEventListener('click', function() {
                document.querySelectorAll('.map-theme-option').forEach(opt => opt.classList.remove('active'));
                this.classList.add('active');
                mapTheme = this.dataset.theme;
                
                if (uploadedFiles.length > 0 && currentTemplate === 'map') {
                    generatePoster();
                }
            });
        });

        // Route style switching
        document.querySelectorAll('.route-style-option').forEach(option => {
            option.addEventListener('click', function() {
                document.querySelectorAll('.route-style-option').forEach(opt => opt.classList.remove('active'));
                this.classList.add('active');
                routeStyle = this.dataset.style;
                
                if (uploadedFiles.length > 0 && currentTemplate === 'route') {
                    generatePoster();
                }
            });
        });
    </script>
</body>
</html> 